<template>
	<div class="hcj_switch" @click="clickSwitch">
		<span 
		class="hcj_switch_core"
		:class="{'is_checked':value}"
		ref='switchBg'
		>
			<span 
			:class="{'is-switch_button':value}"
			class="hcj_switch_button"
			:style="{'background-color': circleColor}"></span>
		</span>
		<input type="checkbox" ref="input" :name="name">
	</div>
</template>

<script>
	export default {
		name: 'hcj-switch',
		props: {
			value: {
				type: Boolean,
				default: false
			},
			name: {
				type: String,
				default: ''
			},
			activeColor: {
				type: String,
				default: ''
			},
			inactiveColor: {
				type: String,
				default: ''
			},
			circleColor: {
				type: String,
				default: '#fff'
			}
		},
		mounted() {
			this.setStyle()
			this.$refs.input.checked = this.value
		},
		methods: {
			clickSwitch() {
				this.$emit('input',!this.value)
				this.$nextTick().then(()=>{
					this.setStyle()
				})
				this.$refs.input.checked = this.value
			},
			setStyle() {
				if(this.activeColor || this.inactiveColor) {
					let color = this.value ? this.inactiveColor : this.activeColor;
					this.$refs.switchBg.style.backgroundColor = color
				}
			}
		}
	}
</script>

<style scoped>
	.hcj_switch {
		display: inline-flex;
		align-items: center;
		position: relative;
		font-size: 14px;
		line-height: 20px;
		height: 20px;
		vertical-align: middle;
	}
	.hcj_switch_core {
		margin: 0;
		display: inline-block;
		position: relative;
		width: 40px;
		height: 20px;
		border: 1px solid gray;
		outline: none;
		border-radius: 10px;
		box-sizing: border-box;
		background: #dcdfe6;
		cursor: pointer;
		transition: border-color .3s,background-color .3s;
		vertical-align: middle;
	}
	.hcj_switch_button {
		position: absolute;
		top: 1px;
		left: 1px;
		border-radius: 100%;
		transition: all .3s;
		width: 16px;
		height: 16px;
	}
	
	.is_checked {
		background-color: #2c3e50;
		border-color: #2c3e50;
	}
	.is-switch_button{
		transform: translateX(20px);
	}
	input {
		position: absolute;
		width: 0;
		height: 0;
		opacity: 0;
		margin: 0;
	}
</style>